﻿using System;
using System.Globalization;
using System.Windows.Forms;
using Data.Model;
using DataAccess.SystemManage;
using Ninject;
using WinForm.Helper;

namespace WinForm.Common
{
    public partial class EidtRolePrivilege : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly ISysRole _sysRole = Kernel.Get<ISysRole>();

        public EidtRolePrivilege()
        {
            InitializeComponent();
        }

        public EidtRolePrivilege(int id)
        {
            InitializeComponent();
            if (id > 0)
            {
                var role = _sysRole.GetRole(id);
                lbRoleID.Text = id.ToString(CultureInfo.InvariantCulture);
                txtRoleName.Text = role.Obj.Rolename;

                RefreshListBox(id);

            }
        }

        private void RefreshListBox(int id)
        {
            var selectedPrivileges = _sysRole.GetRolePrivileges(1, int.MaxValue, id);
            var unselectedPrivileges = _sysRole.GetRoleUnPrivileges(id, 1, int.MaxValue);

            lbSelectedPrivilege.DataSource = selectedPrivileges.Obj.Records;
            lbSelectedPrivilege.DisplayMember = "PrivilegeName";
            lbSelectedPrivilege.ValueMember = "Privilegeid";

            lbUnseletedPrivilege.DataSource = unselectedPrivileges.Obj.Records;
            lbUnseletedPrivilege.DisplayMember = "privilegeName";
            lbUnseletedPrivilege.ValueMember = "privilegeid";

        }

        private void btnAddRolePrivilege_Click(object sender, EventArgs e)
        {
            var item = lbUnseletedPrivilege.SelectedItem;
            if (item != null)
            {
                var pri = (Privilege)item;
                var rolePrivilege = new RolePrivilege
                {
                    Roleid = Convert.ToInt32(lbRoleID.Text),
                    Privilegeid = pri.Privilegeid,
                    Privilegename = pri.Privilegename
                };
                _sysRole.CreateUpdateRolePrivilege(rolePrivilege);
            }

            RefreshListBox(Convert.ToInt32(lbRoleID.Text));
        }

        private void btnSubRolePrivilege_Click(object sender, EventArgs e)
        {
            var item = lbSelectedPrivilege.SelectedItem;
            if (item != null)
            {
                var pri = (RolePrivilege)item;
                _sysRole.DeleteRolePrivilege(pri.Id);
            }

            RefreshListBox(Convert.ToInt32(lbRoleID.Text));
        }
    }
}
